package org.demo.test.thread.timer;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.junit.Test;

/**
 * 定时器测试
 * @author yaohui
 */
public class TimerTestDemo {
	
	Logger logger = Logger.getLogger(TimerTestDemo.class);

	/**
	 * 本案例测试Timer的任务调度是非并行处理的
	 */
	@Test
	public void task(){
		// Timer类实际包括了一个循环执行的TimerThread线程，以及对应的TASK任务队列
		Timer timer = new Timer("任务调度线程",true);
		Object obj = new Object();
		TimerTask task1 = new TimerTask(){
			@Override
			public void run() {
				try {
					logger.info("task1:任务开始执行!");
					Thread.sleep(10000);
					logger.info("task1:任务执行结束!");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		TimerTask task2 = new TimerTask(){
			@Override
			public void run() {
				try {
					logger.info("task2:任务开始执行!");
					Thread.sleep(10000);
					logger.info("task2:任务执行结束!");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		// 如下：执行效果将按顺序执行
		timer.schedule(task1, 0, 5000);
		timer.schedule(task2, 0, 5000);
		synchronized (obj) {
			try {
				obj.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 本案例测试ScheduledExecutorService类进行定时任务的并行调度
	 * 实质上相比较Timer采用了多线程分别调度任务
	 */
	@Test
	public void ScheduledExecutorServiceTest(){
		// 线程池如果设置为1，则实际效果与单个Timer一样
		ScheduledExecutorService es = Executors.newScheduledThreadPool(2);
		TimerTask task1 = new TimerTask(){
			@Override
			public void run() {
				try {
					logger.info(Thread.currentThread().getName()+" task1:任务开始执行!");
					Thread.sleep(5000);
					logger.info(Thread.currentThread().getName()+" task1:任务执行结束!");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		TimerTask task2 = new TimerTask(){
			@Override
			public void run() {
				try {
					logger.info(Thread.currentThread().getName()+" task2:任务开始执行!");
					Thread.sleep(5000);
					logger.info(Thread.currentThread().getName()+" task2:任务执行结束!");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		es.scheduleWithFixedDelay(task1, 0, 2, TimeUnit.SECONDS);
		es.scheduleWithFixedDelay(task2, 0, 2, TimeUnit.SECONDS);
		synchronized (es) {
			try {
				es.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
